package com.koron.css2.clientCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.clientCenter.Enum.ProcessStateEnum;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.bean.UserBean;
import com.koron.css2.clientCenter.bean.UserInfoMerge;
import com.koron.css2.clientCenter.bean.UserInfoMergeDetail;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMergeDetailMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMergeMapper;
import com.koron.css2.clientCenter.queryBean.UserInfoMergeDetailQuery;
import com.koron.css2.clientCenter.queryBean.UserInfoMergeQuery;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.BusinessAreaMapper;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 根据证件号码查询相关的用户数据
 *
 * @author 朱超
 * @since 2021-12-24 15:15:08
 */
@Service
public class UserInfoMergeSingle implements ServerInterface {

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            UserInfoMergeMapper userInfoMergeMapper = factory.getMapper(UserInfoMergeMapper.class);
            UserInfoMergeDetailMapper userInfoMergeDetailMapper = factory.getMapper(UserInfoMergeDetailMapper.class);
            UserInfoMapper userInfoMapper = factory.getMapper(UserInfoMapper.class);
            CtmInfoMapper ctmInfoMapper = factory.getMapper(CtmInfoMapper.class);
            BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);

            Map<String,Map> areaNameIdMap = businessAreaMapper.getNameAndId();

            // 1. 根据请求json获取实例query
            UserInfoMergeQuery userInfoMergeQuery = JsonUtils.objectToPojo(req.getData(), UserInfoMergeQuery.class);
            // 2. 查询并户数据
            UserInfoMerge userInfoMerge = userInfoMergeMapper.getSingle(userInfoMergeQuery);
            String certNo = userInfoMerge.getCertNo();
            // 3. 查询并户详情数据
            String processState = userInfoMerge.getProcessState();
            List<UserInfoMergeDetail> userInfoMergeDetailList = new ArrayList<>();
            // 3.1 草稿状态下根据certNo查询
            if (processState.equals(ProcessStateEnum.DRAFT.getState())) {
                // 3.1.1 查询当前证件号码下的所有用户(查出USER_NO, SETUP_METER_ADDR, CTM_NO, ACCOUNT_NO)
                UserInfoMergeDetailQuery userInfoMergeDetailQuery = new UserInfoMergeDetailQuery();
                userInfoMergeDetailQuery.setCertNo(certNo);
                userInfoMergeDetailList = userInfoMergeDetailMapper.getListFromUserInfo(userInfoMergeDetailQuery);
                // 3.1.2 查询当前证件号码下的所有客户编码
                List<String> ctmNoList = userInfoMapper.getCtmNoListByCertNo(certNo);
                // 3.1.3 查询客户编码列表下的所有的账户编码
                Map<String, List<String>> ctmToAccountMap = new HashMap<>();
                if (ctmNoList != null && ctmNoList.size() > 0) {
                    List<UserInfoMergeDetail> ctmToAccountList = userInfoMapper.getAccountNoListByCTmList(ctmNoList);
                    // 3.1.4 根据客户编码聚合账户编码列表
                    ctmToAccountMap = ctmToAccountList.stream().collect(Collectors.groupingBy(
                            UserInfoMergeDetail::getCtmNo, Collectors.mapping(UserInfoMergeDetail::getAccountNo, Collectors.toList())));
                }
                // 3.1.5 查询客户对应的用户数量
                Map<String, Map> ctmUserAmountMap = new HashMap<>();
                if (ctmNoList != null && ctmNoList.size() > 0) {
                    ctmUserAmountMap = userInfoMapper.getCtmUserAmountByCtmNoList(ctmNoList);
                }
                for (UserInfoMergeDetail userInfoMergeDetail : userInfoMergeDetailList) {
                    String ctmNo = userInfoMergeDetail.getCtmNo();
                    // 3.1.6 根据ctm_no查询ctm_name, ctm_addr
                    CtmInfoBean ctmInfoBean = ctmInfoMapper.getCtmInfoByCtmNo(userInfoMergeDetail.getCtmNo(), 1);
                    userInfoMergeDetail.setCtmAddr(ctmInfoBean.getCtmAddr());
                    userInfoMergeDetail.setCtmName(ctmInfoBean.getCtmName());
                    userInfoMergeDetail.setCtmNoList(ctmNoList);
                    if (!ctmUserAmountMap.isEmpty()) {
                        userInfoMergeDetail.setCtmUserAmount(Integer.parseInt(ctmUserAmountMap.get(ctmNo).get("ctmUserAmount").toString()));
                    }
                    // 3.1.7 根据account_no查询accountUserAmount
                    Integer accountUserAmount = userInfoMapper.getAccountUserAmountByAccountNo(userInfoMergeDetail.getAccountNo());
                    userInfoMergeDetail.setAccountUserAmount(accountUserAmount);
                    // 3.1.8 根据ctmNo查询当前客户下对应的所有账户
//                List<String> accountNoList = userInfoMapper.getAccountNoListByCtmNo(userInfoMergeDetail.getCtmNo());
                    if (!ctmToAccountMap.isEmpty()) {
                        userInfoMergeDetail.setAccountNoList(ctmToAccountMap.get(ctmNo));
                    }
                    // 3.1.9 将所有数据设置成从客户
                    userInfoMergeDetail.setMainCtmFlag(0);
                    // 3.1.10 businessArea->businessAreaName
                    String businessArea = userInfoMergeDetail.getBusinessArea();
                    if (StringUtils.isNotEmpty(businessArea)) {
                        userInfoMergeDetail.setBusinessAreaName(areaNameIdMap.get(businessArea).get("area_name").toString());
                    }
                }
                // 3.1.11 将第一条数据设置成主客户
                userInfoMergeDetailList.get(0).setMainCtmFlag(1);

            } // 3.2 其他状态下直接查询并户详情表
            else {
                UserInfoMergeDetailQuery userInfoMergeDetailQuery = new UserInfoMergeDetailQuery();
                userInfoMergeDetailQuery.setMergeCode(userInfoMergeQuery.getBillNo());
                userInfoMergeDetailList = userInfoMergeDetailMapper.getList(userInfoMergeDetailQuery);
                // 4. 查询当前证件号码下的所有客户编码
                List<String> ctmNoList = userInfoMapper.getCtmNoListByCertNo(certNo);
                // 5. 查询客户编码列表下的所有的账户编码
                Map<String, List<String>> ctmToAccountMap = new HashMap<>();
                if (ctmNoList != null && ctmNoList.size() > 0) {
                    List<UserInfoMergeDetail> ctmToAccountList = userInfoMapper.getAccountNoListByCTmList(ctmNoList);
                    // 5.1 根据客户编码聚合账户编码列表
                    ctmToAccountMap = ctmToAccountList.stream().collect(Collectors.groupingBy(
                            UserInfoMergeDetail::getCtmNo, Collectors.mapping(UserInfoMergeDetail::getAccountNo, Collectors.toList())));
                }
                // 6. 查询客户对应的用户数量
                Map<String, Map> ctmUserAmountMap = new HashMap<>();
                if (ctmNoList != null && ctmNoList.size() > 0) {
                    ctmUserAmountMap = userInfoMapper.getCtmUserAmountByCtmNoList(ctmNoList);
                    logger.error(String.valueOf(ctmUserAmountMap));
                }
                // 7. ctmNoList,accountNoList,ctmUserAmount,accountUserAmount
                for (UserInfoMergeDetail userInfoMergeDetail : userInfoMergeDetailList) {
                    String ctmNo = userInfoMergeDetail.getCtmNo();
                    // 8.1 ctmUserAmount
                    if (!ctmUserAmountMap.isEmpty()) {
                        Map<String,Object> map = ctmUserAmountMap.get(ctmNo);
                        // 20220407: 兼容map为空的情况
                        if (map == null) {
                            userInfoMergeDetail.setCtmUserAmount(0);
                        } else {
                            Object object = map.get("ctmUserAmount");
                            String string = object.toString();
                            userInfoMergeDetail.setCtmUserAmount(Integer.parseInt(string));
                        }
                    }
                    // 8.2 accountUserAmount
                    Integer accountUserAmount = userInfoMapper.getAccountUserAmountByAccountNo(userInfoMergeDetail.getAccountNo());
                    userInfoMergeDetail.setAccountUserAmount(accountUserAmount);
                    // 8.3 ctmNoList
                    userInfoMergeDetail.setCtmNoList(ctmNoList);
                    // 8.4 accountNoList
                    if (!ctmToAccountMap.isEmpty()) {
                        userInfoMergeDetail.setAccountNoList(ctmToAccountMap.get(userInfoMergeDetail.getCtmNo()));
                    }
                    // 8.5 businessArea->businessAreaName
                    // 8.5.1 并户详情中并未存储businessArea，所以通过userNo去用户表中查询
                    UserBean userBean = userInfoMapper.getUserInfoByUserNo(userInfoMergeDetail.getUserNo(),UserBean.USER);
                    String businessArea = userBean.getBusinessArea();
                    userInfoMergeDetail.setBusinessAreaName(areaNameIdMap.get(businessArea).get("area_name").toString());
                }
            }
            // 9. 添加并户详情数据
            userInfoMerge.setUserInfoMergeDetailList(userInfoMergeDetailList);
            // 10. 返回数据
            MessageBean<UserInfoMerge> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "单条并户详情查询成功", UserInfoMerge.class);
            msg.setData(userInfoMerge);
            return msg;
        } catch (Exception e) {
            logger.error("单条并户详情查询失败", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "单条并户详情查询失败", void.class);
        }
    }
}
